package ink.zhaohui.bytebuddy;


import static net.bytebuddy.matcher.ElementMatchers.isGetter;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isSetter;
import static net.bytebuddy.matcher.ElementMatchers.not;

import ink.zhaohui.bytebuddy.interceptor.MonitorMethodTime;
import java.security.ProtectionDomain;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.utility.JavaModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AgentTransformer implements AgentBuilder.Transformer {

  private static final String CONTROLLER_NAME = "ink.zhaohui";
  final Logger logger = LoggerFactory.getLogger(AgentTransformer.class);

  @Override
  public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
      TypeDescription typeDescription, ClassLoader classLoader, JavaModule module,
      ProtectionDomain protectionDomain) {
    DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition<?> intercept = builder
        .method(isMethod().and(not(isSetter())).and(not(isGetter()))
        ).intercept(MethodDelegation.to(new MonitorMethodTime()));
    // 不能返回builder,因为bytebuddy库里的类基本都是不可变的,修改之后需要返回修改后的对象避免修改丢失
    return intercept;
  }
}
